import requests
import os
from datetime import datetime
from bs4 import BeautifulSoup
import zipfile

BLOOM_COM = "https://i-bloom.shop/search?options%5Bprefix%5D=last&q="
NIGIGEN_COM = "https://i-bloom.shop/zh-zh"
BLOOM_DIR = 'download/bloom/'
import random


def get_bloom_result(data):
    barcode = data['barcode']

    url = BLOOM_COM + barcode
    print(url)
    response = requests.get(url)
    if response.status_code != 200:
        exit()

    soup = BeautifulSoup(response.text,'html.parser')
    a_element = soup.find('a',{'class':'full-unstyled-link'})
    a_href = a_element['href']
    
    second_url = NIGIGEN_COM + a_href
    response = requests.get(second_url)
    if response.status_code != 200:
        exit()

    soup = BeautifulSoup(response.text,'html.parser')
    ul = soup.find('ul',{'class':'thumbnail-list'})
    img_srcs = [image['src'] for image in ul.find_all('img') ]

    # 把小图变成大图
    for index,item in enumerate(img_srcs) :
        img_srcs[index] = 'https:'+ item.replace("=84", "", 2)
    # print(img_srcs)
    # exit()
    # 生成文件夹
    now = datetime.now()
    year = now.year
    month = now.month
    day = now.day
    today = str(year) + '-' + str(month) + '-' + str(day)
    ymd = os.path.join(BLOOM_DIR, today)
    save_dir = os.path.join(ymd, barcode)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    download_bloom_image(img_srcs,save_dir)
    return {"barcode":barcode,"images":img_srcs,"date":today}

def download_bloom_image(urlArr, save_dir):
    # print(urlArr)
    img_path = []
    filenameArr = []
    for url in urlArr:
        # splitted = url.split('/')
        # str1 = splitted[len(splitted)-1]
        # 默认图片格式为jpg
        filename = str(random.randint(10000, 99999)) + '.jpg'
        response = requests.get(url)
        if response.status_code == 200:
            with open(os.path.join(save_dir, filename), "wb") as f:
                f.write(response.content)
            print("图片下载成功:", filename)
        else:
            print("图片下载失败")
    return {'img_path':img_path,'filename':filenameArr}


# 创建一个滚去后的文件路径
def create_zip(zip_filename, folder_to_zip):
    # 创建一个 zip 文件，'w' 表示写入模式
    with zipfile.ZipFile(zip_filename, 'w') as zip_file:
        # 遍历指定文件夹中的所有文件
        for foldername, subfolders, filenames in os.walk(folder_to_zip):
            for filename in filenames:
                # 创建文件的完整路径
                file_path = os.path.join(foldername, filename)
                # 将文件写入 zip 文件
                zip_file.write(file_path, os.path.relpath(file_path, folder_to_zip))
    print(f"{zip_filename} 创建成功!")

        